package cn.yunyichina.provider.base.service.impl;

import cn.yunyichina.provider.base.dao.OrgAppDao;
import cn.yunyichina.provider.iface.entity.base.Org;
import cn.yunyichina.provider.iface.entity.base.OrgApp;
import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.framework.page.PageInfo;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.utils.convert.JsonUtils;
import cn.yunyichina.utils.security.MD5Util;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by CJun on 2016/10/28.
 */
@Service("orgappServiceImpl")
public class OrgAppServiceImpl {

    @Autowired
    private OrgAppDao orgAppDao;

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    static Logger log = LoggerFactory.getLogger(OrgAppServiceImpl.class);

    /**
     * 组织应用列表查询
     * @param data(可根据：组织ID、是否禁用标志进行查询，查询字段可继续扩展。当page_num和page_size为空时表示不分页返回所有数据)
     * @return
     * @author CJun
     */
    public Response listOrgApp(String data) {
        //定义返回结果
        Response response = new Response();
        Map<String, Object> result = new HashMap<>();

        //定义返回列表和分页信息
        List<OrgApp> list = null;
        PageInfo pageInfo = new PageInfo();

        //定义返回码和返回信息
        String resultCode = "1000";
        String resultMessage = "执行成功";

        try {
            //获取入参
            log.info("【组织应用列表查询】开始, 入参->"+data);
            OrgApp orgApp = JsonUtils.parseObject(data, OrgApp.class);
            Map<String, String> maps = JsonUtils.parseObject(data, Map.class);
//            String orgAppId = maps.get("org_app_id");
//            String enableFlag = maps.get("enable_flag");
            String pageNum = maps.get("page_num");
            String pageSize = maps.get("page_size");

//            //参数组装
//            OrgApp orgApp = new OrgApp();
//            if(StringUtils.isNotBlank(orgAppId)){
//                orgApp.setOrgId(orgAppId);
//            }else if(StringUtils.isNotBlank(enableFlag)){
//                orgApp.setEnableFlag(Short.parseShort(enableFlag));
//            }

            //查询，如需分页则计算分页信息
            if(StringUtils.isNotBlank(pageNum) && StringUtils.isNotBlank(pageSize)){
                long count = orgAppDao.selectCount(orgApp);
                pageInfo.setTotal(count);
                pageInfo.setPageNum(Integer.valueOf(pageNum));
                pageInfo.setPageSize(Integer.valueOf(pageSize));
                pageInfo.setPages((pageInfo.getTotal().intValue() + pageInfo.getPageSize() - 1) / pageInfo.getPageSize());
                list = orgAppDao.select(orgApp , pageInfo);
            }else if(StringUtils.isBlank(pageNum) && StringUtils.isBlank(pageSize)){
                list = orgAppDao.select(orgApp);
            }else{
                resultCode = "1001";
                resultMessage = "参数有误:" + "page_num不能为空或者page_size不能为空";
            }
        } catch (Exception e) {
            resultCode = "1999";
            resultMessage = "系统异常:" + e.getMessage();
            e.printStackTrace();
        } finally {
            //组装返回结果
            result.put("list" , list);
            result.put("page_info" , pageInfo);
            response.setResult(JsonUtils.toJsonString(result));
            response.setResultCodeAndMessage(resultCode, resultMessage);
            log.info("【组织应用列表查询】结束, " + resultCode + ", " + resultMessage);
            return response;
        }

    }


    /**
     * 组织应用保存
     * @param data
     * @return
     * @author CJun
     */
    public Response saveOrgApp(String data) {

        //定义返回结果
        Response response = new Response();
        OrgApp orgApp  = JsonUtils.parseObject(data, OrgApp.class);

        //定义返回码和返回信息
        String resultCode = "1000";
        String resultMessage = "执行成功";

        //定义应用编码
        String orgAppCode = "";

        try {
            //获取入参
            log.info("【添加组织应用】开始, 入参->"+data);

            String orgAppName = orgApp.getOrgAppName();
            String description = orgApp.getDescription();
            String orgId = orgApp.getOrgId();
            String orgName = orgApp.getOrgName();

            //检查参数合法性
            boolean check = true;
            if(StringUtils.isBlank(orgAppName)){
                check = false;
                resultCode = "1001";
                resultMessage = "参数有误:" + "org_app_name不能为空";
            }else if(StringUtils.isBlank(description)){
                check = false;
                resultCode = "1001";
                resultMessage = "参数有误:" + "description不能为空";
            }else if(StringUtils.isBlank(orgId)){
                check = false;
                resultCode = "1001";
                resultMessage = "参数有误:" + "org_id不能为空";
            }else if(StringUtils.isBlank(orgName)){
                check = false;
                resultCode = "1001";
                resultMessage = "参数有误:" + "org_name不能为空";
            }else{
                //自动生成应用编码（暂时处理）
                orgAppCode = "yyt" + MD5Util.string2MD5_16(orgAppName);

                //查询是否存在相同编号的组织应用
                OrgApp orgAppCheck = new OrgApp();
                orgAppCheck.setOrgAppCode(orgAppCode);
                List<OrgApp> list = orgAppDao.select(orgAppCheck);
                if(list != null && list.size() > 0){
                    if(!list.get(0).getId().equals(orgApp.getId())) {
                        check = false;
                        resultCode = "1003";
                        resultMessage = "存在重复信息:" + "组织应用编号已存在";
                    }
                }
            }

            //检查不通过，结束流程
            if(!check){
                //组装返回结果
                response.setResult(JsonUtils.toJsonString(orgApp));
                response.setResultCodeAndMessage(resultCode, resultMessage);
                log.info("【添加组织应用】结束, " + resultCode + ", " + resultMessage);
                return response;
            }

            //参数组装

            orgApp.setOrgAppCode(orgAppCode);
            orgApp.setOrgAppName(orgAppName);
            orgApp.setDescription(description);
            orgApp.setOrgId(orgId);
            orgApp.setOrgName(orgName);
            if(orgApp.getEnableFlag() == null) {
                orgApp.setEnableFlag(Short.parseShort("1"));
            }

            //保存数据
            //参数组装
            if(StringUtils.isBlank(orgApp.getId())){
                orgApp.setId(PKGenerator.generateId());
                orgApp.setCreatedTime(simpleDateFormat.format(new Date()));
                orgAppDao.insert(orgApp);
            }else{
                //更新
                orgApp.setUpdateTime(simpleDateFormat.format(new Date()));
                orgAppDao.update(orgApp);
            }

        } catch (NumberFormatException e) {
            resultCode = "1999";
            resultMessage = "系统异常:" + e.getMessage();
            e.printStackTrace();
        } finally {
            //组装返回结果
            response.setResult(JsonUtils.toJsonString(orgApp));
            response.setResultCodeAndMessage(resultCode, resultMessage);
            log.info("【添加组织应用】结束, " + resultCode + ", " + resultMessage);
            return response;
        }

    }



    /**
     * 修改组织应用
     * @param data
     * @return
     * @author CJun
     */
    public Response updateOrgApp(String data) {

        //定义返回结果
        Response response = new Response();
        OrgApp orgApp = new OrgApp();

        //定义返回码和返回信息
        String resultCode = "1000";
        String resultMessage = "执行成功";

        try {
            //获取入参
            log.info("【修改组织应用】开始, 入参->"+data);
            Map<String, String> maps = JsonUtils.parseObject(data, Map.class);
            String orgAppId = maps.get("org_app_id");
            String orgAppName = maps.get("org_app_name");
            String description = maps.get("description");
            String enableFlag = maps.get("enable_flag");

            //检查参数合法性
            boolean check = true;
            if(StringUtils.isBlank(orgAppId)){
                check = false;
                resultCode = "1001";
                resultMessage = "参数有误:" + "org_app_id不能为空";
            }

            //检查不通过，结束流程
            if(!check){
                //组装返回结果
                response.setResult(JsonUtils.toJsonString(orgApp));
                response.setResultCodeAndMessage(resultCode, resultMessage);
                log.info("【修改组织应用】结束, " + resultCode + ", " + resultMessage);
                return response;
            }

            //参数组装
            orgApp.setId(orgAppId);
            if(StringUtils.isNotBlank(orgAppName)){
                orgApp.setOrgAppName(orgAppName);
            }
            if(StringUtils.isNotBlank(description)){
                orgApp.setDescription(description);
            }
            if(StringUtils.isNotBlank(enableFlag)){
                orgApp.setEnableFlag(Short.parseShort(enableFlag));
            }
            orgApp.setUpdateTime(simpleDateFormat.format(new Date()));

            //保存数据
            orgAppDao.update(orgApp);
        } catch (NumberFormatException e) {
            resultCode = "1999";
            resultMessage = "系统异常:" + e.getMessage();
            e.printStackTrace();
        } finally {
            //组装返回结果
            response.setResult(JsonUtils.toJsonString(orgApp));
            response.setResultCodeAndMessage(resultCode, resultMessage);
            log.info("【修改组织应用】结束, " + resultCode + ", " + resultMessage);
            return response;
        }

    }


    /**
     * 删除组织应用
     * @param data
     * @return
     * @author CJun
     */
    public Response deleteOrgApp(String data) {
        //定义返回结果
        Response response = new Response();
        OrgApp orgApp = new OrgApp();

        //定义返回码和返回信息
        String resultCode = "1000";
        String resultMessage = "执行成功";

        try {
            //获取入参
            log.info("【删除组织应用】开始, 入参->"+data);
            Map<String, String> maps = JsonUtils.parseObject(data, Map.class);
            String orgAppId = maps.get("org_app_id");

            //检查参数合法性
            boolean check = true;
            if(StringUtils.isBlank(orgAppId)){
                check = false;
                resultCode = "1001";
                resultMessage = "参数有误:" + "org_id不能为空";
            }else{
                //查询是否存在该组织应用
                OrgApp orgAppCheck = new OrgApp();
                orgAppCheck.setId(orgAppId);
                List<OrgApp> list = orgAppDao.select(orgAppCheck);
                if(list == null || list.size() == 0){
                    check = false;
                    resultCode = "1004";
                    resultMessage = "该记录不存在：" + "无法删除";
                }
            }

            //检查不通过，结束流程
            if(!check){
                //组装返回结果
                response.setResult(JsonUtils.toJsonString(orgApp));
                response.setResultCodeAndMessage(resultCode, resultMessage);
                log.info("【修改组织应用】结束, " + resultCode + ", " + resultMessage);
                return response;
            }

            //参数组装
            orgApp.setId(orgAppId);

            //保存数据
            orgAppDao.delete(orgApp);
        } catch (NumberFormatException e) {
            resultCode = "1999";
            resultMessage = "系统异常:" + e.getMessage();
            e.printStackTrace();
        } finally {
            //组装返回结果
            response.setResult(JsonUtils.toJsonString(orgApp));
            response.setResultCodeAndMessage(resultCode, resultMessage);
            log.info("【删除组织应用】结束, " + resultCode + ", " + resultMessage);
            return response;
        }

    }
    /**
     * 根据appCode 获得OrgApp对象
     * <br>内部调用接口
     * @param orgAppCode
     * @return 如果没有找到，返回null
     */
    public OrgApp getByAppCode(String orgAppCode) {
    	Map<String,Object> mapParam = new HashMap<>();
		mapParam.put("org_app_code", orgAppCode);
		Response response = getOrgapp(JsonUtils.toJsonString(mapParam));
		if ("0".equals(response.getResultCode())) {
			return JsonUtils.parseObject(response.getResult(),OrgApp.class);
		}
		else {
			return null;
		}
    }
    
    public Response getOrgapp(String data) {
        //定义返回结果
        Response response = new Response();

        //定义返回码和返回信息
        String resultCode = "0";
        String resultMessage = "执行成功";

        try {
            // 获取入参
            log.info("【组织应用列表查询】开始, 入参->" + data);
            Map<String, String> maps = JsonUtils.parseObject(data, Map.class);
            String orgAppCode = maps.get("org_app_code");

            // 参数组装
            OrgApp orgapp = new OrgApp();
            orgapp.setOrgAppCode(orgAppCode);

            // 查询，如需分页则计算分页信息
            if (StringUtils.isNotBlank(orgAppCode)) {
                List<OrgApp> list = orgAppDao.select(orgapp);
                if (CollectionUtils.isEmpty(list)) {
                    resultCode = "1009";
                    resultMessage = "org_app_code对应的数据不存在";
                } else {
                    response.setResult(JsonUtils.toJsonString(list.get(0)));
                }
            } else {
                resultCode = "1001";
                resultMessage = "参数有误:" + "org_app_code不能为空";
            }
        } catch (Exception e) {
            resultCode = "1999";
            resultMessage = "系统异常:" + e.getMessage();
            log.error("getOrgapp error", e);
        } finally {
            response.setResultCodeAndMessage(resultCode, resultMessage);
            log.info("【组织应用列表查询】结束, " + resultCode + ", " + resultMessage);
            return response;
        }

    }

}
